/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn;

import cn.webrx.mapper.DbMapper;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.File;

/**
 * <p>Project: mybatis2022 - MyDemo
 * <p>Powered by webrx On 2022-04-11 09:51:16
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class MyDemo {
    SqlSessionFactory sf;
    SqlSession ss;
    DbMapper dm;

    @BeforeEach
    void init() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl("jdbc:mysql:/db");
        ds.setUsername("root");

        //事务对象
        TransactionFactory tx = new JdbcTransactionFactory();
        //开发环境对象
        Environment env = new Environment("development", tx, ds);
        //建立配置文件
        Configuration cfg = new Configuration(env);

        //增加Mapper映射接口时DbMapper.java，会自动添加同名的映射配置文件DbMapper.xml
        //cfg.addMapper(DbMapper.class);

        //增加Mapper映射接口时DbMapper.java，会自动添加同名的映射配置文件DbMapper.xml 指定包
        cfg.addMappers("cn.webrx.mapper");

        //建立SqlSessionFactory sf
        sf = new SqlSessionFactoryBuilder().build(cfg);

        //会自动批量加载/resources/mappers/*.xml
        var xml = "mapper/";
        var p = Thread.currentThread().getContextClassLoader().getResource(xml).getPath();
        var f = new File(p);
        for (String s : f.list()) {
            if (s.endsWith(".xml")) {
                var t = xml + s;
                var is = Thread.currentThread().getContextClassLoader().getResourceAsStream(t);
                new XMLMapperBuilder(is, cfg, t, cfg.getSqlFragments()).parse();
            }
        }

        ss = sf.openSession();
        dm = ss.getMapper(DbMapper.class);
    }

    @Test
    void t1(){
        System.out.println(dm.version());
        System.out.println(dm.dbs());
    }
}
